using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2009
// by DotNetNuke Corporation
//

using System.Text;
using DotNetNuke.Security.Roles;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Users;
using System.Text.RegularExpressions;

namespace DotNetNuke.Security.Permissions.Controls
{

    public class WorkflowStatePermissionsGrid : PermissionsGrid
    {

        #region "Private Members"

        private int _StateID = -1;
        private WorkflowStatePermissionCollection _WorkflowStatePermissions;
        private List<PermissionInfoBase> _PermissionsList;

        private bool _RefreshGrid = Null.NullBoolean;
        #endregion

        #region "Protected Properties"

        protected override List<PermissionInfoBase> PermissionsList
        {
            get
            {
                if (_PermissionsList == null && _WorkflowStatePermissions != null)
                {
                    _PermissionsList = _WorkflowStatePermissions.ToList();
                }
                return _PermissionsList;
            }
        }

        protected override bool RefreshGrid
        {
            get { return _RefreshGrid; }
        }

        #endregion

        #region "Public Properties"

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets and Sets the StateID
        /// </summary>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public int StateID
        {
            get { return _StateID; }
            set
            {
                _StateID = value;
                _RefreshGrid = true;
                GetWorkflowStatePermissions();
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the Permission Collection
        /// </summary>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public Security.Permissions.WorkflowStatePermissionCollection Permissions
        {
            get
            {
                //First Update Permissions in case they have been changed
                UpdatePermissions();

                //Return the WorkflowStatePermissions
                return _WorkflowStatePermissions;
            }
        }

        #endregion

        #region "Private Methods"

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the WorkflowStatePermissions from the Data Store
        /// </summary>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        private void GetWorkflowStatePermissions()
        {
            _WorkflowStatePermissions = new WorkflowStatePermissionCollection(WorkflowStatePermissionController.GetWorkflowStatePermissions(this.StateID));
            _PermissionsList = null;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Parse the Permission Keys used to persist the Permissions in the ViewState
        /// </summary>
        /// <param name="Settings">A string array of settings</param>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        private WorkflowStatePermissionInfo ParseKeys(string[] Settings)
        {
            WorkflowStatePermissionInfo objWorkflowStatePermission = new WorkflowStatePermissionInfo();

            //Call base class to load base properties
            base.ParsePermissionKeys(objWorkflowStatePermission, Settings);

            if (string.IsNullOrEmpty(Settings[2]))
            {
                objWorkflowStatePermission.WorkflowStatePermissionID = -1;
            }
            else
            {
                objWorkflowStatePermission.WorkflowStatePermissionID = Convert.ToInt32(Settings[2]);
            }
            objWorkflowStatePermission.StateID = StateID;

            return objWorkflowStatePermission;
        }

        #endregion

        #region "Protected Methods"

        protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess)
        {
            WorkflowStatePermissionInfo objPermission = new WorkflowStatePermissionInfo(permission);
            objPermission.StateID = StateID;
            objPermission.RoleID = roleId;
            objPermission.RoleName = roleName;
            objPermission.AllowAccess = allowAccess;
            objPermission.UserID = userId;
            objPermission.DisplayName = displayName;
            _WorkflowStatePermissions.Add(objPermission, true);

            //Clear Permission List
            _PermissionsList = null;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Updates a Permission
        /// </summary>
        /// <param name="permissions">The permissions collection</param>
        /// <param name="user">The user to add</param>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void AddPermission(ArrayList permissions, UserInfo user)
        {
            //Search TabPermission Collection for the user 
            bool isMatch = false;
            foreach (WorkflowStatePermissionInfo objWorkflowStatePermission in _WorkflowStatePermissions)
            {
                if (objWorkflowStatePermission.UserID == user.UserID)
                {
                    isMatch = true;
                    break;
                }
            }

            //user not found so add new
            if (!isMatch)
            {
                foreach (PermissionInfo objPermission in permissions)
                {
                    if (objPermission.PermissionKey == "REVIEW")
                    {
                        AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true);
                    }
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the Enabled status of the permission
        /// </summary>
        /// <param name="objPerm">The permission being loaded</param>
        /// <param name="role">The role</param>
        /// <param name="column">The column of the Grid</param>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column)
        {
            return !(role.RoleID == AdministratorRoleId);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the Value of the permission
        /// </summary>
        /// <param name="objPerm">The permission being loaded</param>
        /// <param name="role">The role</param>
        /// <param name="column">The column of the Grid</param>
        /// <returns>A Boolean (True or False)</returns>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState)
        {
            string permission = null;

            if (role.RoleID == AdministratorRoleId)
            {
                permission = PermissionTypeGrant;
            }
            else
            {
                //Call base class method to handle standard permissions
                permission = base.GetPermission(objPerm, role, column, defaultState);
            }

            return permission;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the permissions from the Database
        /// </summary>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override ArrayList GetPermissions()
        {
            return WorkflowStatePermissionController.GetPermissionsByStateID(StateID);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Load the ViewState
        /// </summary>
        /// <param name="savedState">The saved state</param>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------

        protected override void LoadViewState(object savedState)
        {
            if ((savedState != null))
            {
                // Load State from the array of objects that was saved with SaveViewState.

                object[] myState = (object[])savedState;

                //Load Base Controls ViewStte
                if ((myState[0] != null))
                {
                    base.LoadViewState(myState[0]);
                }

                //Load StateID
                if ((myState[1] != null))
                {
                    _StateID = Convert.ToInt32(myState[1]);
                }

                //Load WorkflowStatePermissions
                if ((myState[2] != null))
                {
                    _WorkflowStatePermissions = new WorkflowStatePermissionCollection();
                    string state = Convert.ToString(myState[2]);
                    if (!string.IsNullOrEmpty(state))
                    {
                        //First Break the String into individual Keys
                        string[] permissionKeys = Regex.Split(state, "##");
                        foreach (string key in permissionKeys)
                        {
                            string[] Settings = key.Split('|');
                            _WorkflowStatePermissions.Add(ParseKeys(Settings));
                        }
                    }
                }
            }

        }

        protected override void RemovePermission(int permissionID, int roleID, int userID)
        {
            _WorkflowStatePermissions.Remove(permissionID, roleID, userID);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Saves the ViewState
        /// </summary>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override object SaveViewState()
        {
            object[] allStates = new object[3];

            // Save the Base Controls ViewState
            allStates[0] = base.SaveViewState();

            //Save the State Id
            allStates[1] = StateID;

            //Persist the TabPermisisons
            StringBuilder sb = new StringBuilder();
            if (_WorkflowStatePermissions != null)
            {
                bool addDelimiter = false;
                foreach (WorkflowStatePermissionInfo objWorkflowStatePermission in _WorkflowStatePermissions)
                {
                    if (addDelimiter)
                    {
                        sb.Append("##");
                    }
                    else
                    {
                        addDelimiter = true;
                    }
                    sb.Append(BuildKey(objWorkflowStatePermission.AllowAccess, objWorkflowStatePermission.PermissionID, objWorkflowStatePermission.WorkflowStatePermissionID, objWorkflowStatePermission.RoleID, objWorkflowStatePermission.RoleName, objWorkflowStatePermission.UserID, objWorkflowStatePermission.DisplayName));
                }
            }
            allStates[2] = sb.ToString();

            return allStates;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// returns whether or not the derived grid supports Deny permissions
        /// </summary>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override bool SupportsDenyPermissions()
        {
            return true;
        }

        #endregion

        #region "Public Methods"

        public void ResetPermissions()
        {
            GetWorkflowStatePermissions();
            _PermissionsList = null;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Overrides the Base method to Generate the Data Grid
        /// </summary>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------

        public override void GenerateDataGrid()
        {
        }

        #endregion

    }


}
